package com.example.myapplication.fragment;


import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.example.myapplication.R;
import com.example.myapplication.adapter.WorkRecyclerAdapter;
import com.example.myapplication.bean.TeacherInfo;
import com.example.myapplication.bean.WorkInfoemation;
import com.example.myapplication.callback.LoginCallBack;
import com.example.myapplication.helper.PreferencesHelper;
import com.example.myapplication.ic.ILoginInterface;
import com.example.myapplication.ic.ITeacherInterface;
import com.example.myapplication.ic.TeacherInterfaceImpl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class TeacherOwnFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,LoginCallBack {

    private RecyclerView recyclerView;
    private LinearLayoutManager mLayoutManager;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int lastVisibleItem;
    private WorkInfoemation workInfoemation,workinfoemation1;
    private List<WorkInfoemation> list = new ArrayList<>();
    private WorkRecyclerAdapter workRecyclerAdapter;
    private int PAGE = 1;
    private int PAGE_TOTAL;
    private ITeacherInterface iTeacherInterface;
    private String teacher_number;
    private FloatingActionButton fab;

    public TeacherOwnFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_teacher_own,container,false);
        initView(view);
        mLayoutManager=new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL,false);
        recyclerView.setLayoutManager(mLayoutManager);
        workRecyclerAdapter = new WorkRecyclerAdapter(getContext(),list);
        recyclerView.addOnScrollListener(OnSroll);
        recyclerView.setAdapter(workRecyclerAdapter);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.indigo_200,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        iTeacherInterface = new TeacherInterfaceImpl();
        teacher_number = getTeacher_number();
        if(teacher_number==null){
            Snackbar.make(view.findViewById(R.id.frl),"登陆信息失效，请重新登陆！",Snackbar.LENGTH_SHORT).show();
        }else
        iTeacherInterface.getInfo(PAGE+"",getTeacher_number(),this);

        return view;
    }

    public String getTeacher_number(){
        TeacherInfo teacherInfo = PreferencesHelper.getTeacher(getContext());

        if(teacherInfo!=null){
            String teacher_number = teacherInfo.getTeacher_number();
            return teacher_number;
        }
        return null;
    }

    public void initView(View view){
        recyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        fab = (FloatingActionButton) view.findViewById(R.id.fab);
    }

    RecyclerView.OnScrollListener OnSroll  = new RecyclerView.OnScrollListener(){
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            onRecyclerViewStateChanged(newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

        }
    };



    public void onRecyclerViewStateChanged(int newState) {
        if (list == null || list.size() <= 0) {
            Snackbar.make(swipeRefreshLayout, "没有数据得先下拉刷新", Snackbar.LENGTH_SHORT).show();
            return;
        }
        //滚动事件结束并且到达最底端
        if (newState == RecyclerView.SCROLL_STATE_IDLE
                && lastVisibleItem + 1 == workRecyclerAdapter.getItemCount()) {
            if (PAGE < PAGE_TOTAL) {
                LoadMore();
            }else{
                Snackbar.make(swipeRefreshLayout, "没有数据了", Snackbar.LENGTH_SHORT).show();
            }
        }
    }

    public void onPreLoadMore() {
        list.add(workinfoemation1);
        workRecyclerAdapter.notifyDataSetChanged();
    }

    public void onPostLoadMore() {
        PAGE++;
        iTeacherInterface.getInfo(PAGE+"","",this);


    }

    public void LoadMore(){
        onPreLoadMore();
        onPostLoadMore();
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(true);
        list.clear();
        PAGE = 1;
        iTeacherInterface.getInfo(PAGE+"",teacher_number,this);
    }

    @Override
    public void onSuccess(String info) {
        list.remove(workinfoemation1);
        swipeRefreshLayout.setRefreshing(false);
        Log.i("JsonObject", info);
        List<WorkInfoemation> mlist = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(info);
            PAGE_TOTAL = jsonObject.getInt("page");
            JSONArray jsonArray = jsonObject.getJSONArray("info");
            for (int i = 0; i < jsonArray.length(); i++) {
                WorkInfoemation workInfoemation = new WorkInfoemation();
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String workid = jsonObject1.getString("workid");
                String workname = jsonObject1.getString("workname");
                String workinfo = jsonObject1.getString("workinfo");
                String date = jsonObject1.getString("date");
                String teacher_id = jsonObject1.getString("teacher_id");
                String teacher_name = jsonObject1.getString("teacher_name");
                String teacher_email = jsonObject1.getString("teacher_email");
                String teacher_number = jsonObject1.getString("teacher_number");
                String teacher_pic = jsonObject1.getString("teacher_pic");
                teacher_pic = teacher_pic.substring(1);
                workInfoemation.setDate(date);
                workInfoemation.setTeacher_name(teacher_name);
                workInfoemation.setTeacher_email(teacher_email);
                workInfoemation.setTeacher_pic(teacher_pic);
                workInfoemation.setTeacher_number(teacher_number);
                workInfoemation.setTeacher_id(teacher_id);
                workInfoemation.setWorkinfo(workinfo);
                workInfoemation.setWorkname(workname);
                workInfoemation.setWorkid(workid);
                workInfoemation.setType(0);
                mlist.add(workInfoemation);

            }

            list.addAll(mlist);
            workRecyclerAdapter.changeList(list);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFail(String info) {
        Log.i("Fail",info);
      //  Snackbar.make(fab.getRootView(),"出错l"+info,Snackbar.LENGTH_SHORT).show();
    }
}
